package com.mec.web.y2012.ajax;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * Servlet implementation class PostXMLServlet
 */
@WebServlet("/ajax/postXML")
public class PostXMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public PostXMLServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//String xml = readXMLFromRequest(request);
		String xml = AjaxUtil.readStringFromRequest(request);
		
		Document xmlDoc = null;
		try{
			xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
			
		}catch(Exception e){
			logger.error("Parse XML Error: ", e);
		}
		
		//
		NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
		String type = null;
		StringBuffer responseText = new StringBuffer("Selected Pets: ");
		
		for(int i = 0 ; i < selectedPetTypes.getLength(); ++i){
			type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
			responseText.append( " " + type);
		}
		
		//
		response.setContentType("tex/xml");
		response.getWriter().println(responseText.toString());
	}
	
	
	/*private String readXMLFromRequest(HttpServletRequest request){
		StringBuffer xml = new StringBuffer();
		
		String line = null;
		
		try{
			BufferedReader reader = request.getReader();
			while((line = reader.readLine()) != null){
				xml.append(line);
			}
		}catch(Exception e){
			logger.error("Error reading XML: ", e);
		}
		return xml.toString();
	}*/
	
	private static final Logger logger = 
			Logger.getLogger(PostXMLServlet.class);

}
